<?php

namespace App\Models;

use EloquentFilter\Filterable;
use App\Models\Traits\Admin\ActionButtonTrait;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\SoftDeletes;


class AdminUser extends Model
{
    use Filterable, ActionButtonTrait, HasRoles, SoftDeletes;

    protected $appends = ['actionButton'];
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    
    protected $actions = ['edit','set_role','delete'];

    protected $actionUri = 'managers';

    protected $fillable = [
        'name', 'phone', 'password','type','parent_id','avatar','available','last_ip','state'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 
    ];

    public function manager_machine()
    {
        return $this->hasMany(MachineManager::class, 'manager_id', 'id');
    }

    protected static function boot()
    {
        parent::boot();
        //监听添加事件，写入用户类型
        static::creating(function($model){
            $model->type = 1;
            $model->available = 1;
            if($model->avatar){
                $model->avatar = Storage::url(Storage::disk('public')->put('avatars', $model->avatar)); 
            } 
            $model->password = encrypt_str('123456');
        });
        static::updating(function($model){
            $model->type = 1;
            $model->available = 1;
            if(!is_string($model->avatar)){
                $model->avatar = Storage::url(Storage::disk('public')->put('avatars', $model->avatar));
            }
        });
        //管理员作用域
        static::addGlobalScope('type', function (Builder $builder) {
            $builder->where('type', 1);
        });

    }

}
